package com.mall.seckill_mall.controller;

import com.mall.seckill_mall.annotations.AccessLimit;
import com.mall.seckill_mall.common.Result;
import com.mall.seckill_mall.enums.CodeMessage;
import com.mall.seckill_mall.service.SeckillService;
import com.mall.seckill_mall.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@RestController
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    /**
     * 动态生成秒杀地址， 5秒内最多请求5次
     * @return 秒杀地址
     */
    @AccessLimit(period = 5, maxCount = 5)
    @GetMapping("/path/{goodsId}")
    public Result generatePath(@CookieValue("user_token") String userToken
            , @PathVariable("goodsId") String goodsId) {
        if(!StringUtils.hasText(goodsId)) {
            return ResultUtil.error(CodeMessage.INVALID_REQUEST);
        }
        return ResultUtil.success(seckillService.generatePath(userToken, goodsId));
    }

    /**
     * 进行秒杀（核心）
     * @param goodsId 商品ID
     * @param path 动态秒杀地址
     * @param userToken 用户cookie中token
     * @return 秒杀结果
     */
    @PostMapping("/{goodsId}")
    public Result doSeckill(@PathVariable("goodsId") String goodsId
            , @RequestParam("path") String path
            , @CookieValue("user_token") String userToken) {
        //1. 校验地址
        if(!seckillService.validatePath(userToken, goodsId, path)) {
            return ResultUtil.error(CodeMessage.INVALID_PATH);
        }
        //3. 秒杀
        seckillService.doSeckill(userToken, goodsId);
        return ResultUtil.success("排队下单中");
    }

    /**
     * 获取秒杀结果
     *  1. 排队下单中
     *  2. 秒杀失败
     *  3. 已下单请付款
     * @param goodsId 商品ID
     * @param userToken 登录用户token
     */
    @GetMapping("/{goodsId}")
    public Result getSeckillResult(@PathVariable("goodsId") String goodsId
            , @CookieValue("user_token") String userToken) {
        return ResultUtil.success(seckillService.getSeckillResult(userToken, goodsId));
    }

    /**
     * 支付订单
     * @param orderId 订单ID
     */
    @GetMapping("/pay/{orderId}")
    public Result payForOrder(@PathVariable("orderId") String orderId
            , @CookieValue("user_token") String userToken) {
        seckillService.payForSeckill(orderId, userToken);
        return ResultUtil.success("付款成功");
    }

    @GetMapping("/verifyCode/{goodsId}")
    @ResponseBody
    public Result getMiaoshaVerifyCod(HttpServletResponse response
            , @CookieValue("user_token") String userToken, @PathVariable("goodsId") String goodsId) {
        try {
            BufferedImage image  = seckillService.createVerifyCode(goodsId, userToken);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.flush();
            out.close();
            return null;
        }catch(Exception e) {
            e.printStackTrace();
            return ResultUtil.error(CodeMessage.SERVER_ERROR);
        }
    }

    @PostMapping("/checkVerify/{goodsId}")
    public Result checkVarify(@CookieValue("user_token") String userToken
            , @PathVariable("goodsId") String goodsId, @RequestParam("code") int code) {
        boolean ok = seckillService.checkVerify(goodsId, userToken, code);
        return ResultUtil.success(ok);
    }

}
